﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using System.Web;
using Cherry.Agile.Core.Instrumentation;
using Cherry.Agile.Core;
using System.ServiceModel;
using Cherry.Agile.Framework;

namespace Cherry.Agile.ServiceModel {
    /// <summary>
    /// Http生命周期实现
    /// </summary>
    public class HttpContextLifetimeManager : ChannelLifeTimeManager {

        /// <summary>
        /// 清除缓存项
        /// </summary>
        public static void Clear() {
            if (HttpContext.Current == null)
                return;
            var keys = HttpContext.Current.Items.Keys.Cast<object>().ToArray();
            var threadId = System.Threading.Thread.CurrentThread.ManagedThreadId;
            foreach (var key in keys) {
                var container = HttpContext.Current.Items[key] as UnityContainer;
                if (container != null) {
                    HttpContext.Current.Items.Remove(key);
                    container.Dispose();
                    continue;
                }

                var item = HttpContext.Current.Items[key] as IClientChannel;
                if (item == null)
                    continue;

                HttpContext.Current.Items.Remove(key);

                var vals = key.ToString().Split('|');
                if (vals.Length == 2 && vals[1].ToInt() != threadId)
                    continue;
                ServiceFactory.CloseService(item as IDisposable);

            }

        }

        private string key;
        private int threadId;
        /// <summary>
        /// 构造函数
        /// </summary>
        public HttpContextLifetimeManager() {
            threadId = System.Threading.Thread.CurrentThread.ManagedThreadId;
            key = Guid.NewGuid().ToString() + "|" + threadId;
        }

        public override object GetValue() {
            var val = HttpContext.Current != null ? HttpContext.Current.Items[key] : null;
            return val;
        }

        ///// <summary>
        ///// 移除缓存项
        ///// </summary>
        public override void RemoveValue() {
            var val = GetValue();
            if (val != null)
                base.RemoveValue(val as IClientChannel);

            if (HttpContext.Current != null)
                HttpContext.Current.Items.Remove(key);
        }

        /// <summary>
        /// 设置缓存项
        /// </summary>
        /// <param name="newValue"></param>
        public override void SetValue(object newValue) {
            if (HttpContext.Current != null)
                HttpContext.Current.Items[key] = newValue;
        }

        public override void TearDown() {
            Clear();
        }

    }
}
